package com.miszczu.bo;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.miszczu.dao.GradesDao;
import com.miszczu.dao.UsersDao;
import com.miszczu.model.Grades;
import com.miszczu.model.Users;

@Service
public class GradesBoImpl implements GradesBo {

	@Autowired
	GradesDao gradesDao;
	
	@Autowired
	UsersDao usersDao;
	
	private Double calculateAverage(List<Grades> grades) {
		
		double avg;
		int numberOfGrades = grades.size();
		
		if(numberOfGrades == 0) {
			return 0.0;
		}
		
		double sum = 0;
		for(Grades grade : grades) {
			sum+=grade.getGradeValue();
		}
		
		avg = sum / numberOfGrades;
		
		return avg;
		
	}
	
	public LinkedHashMap<Users, List<Grades>> getGrades(Integer classId,
			Integer subjectId) {

		List<Object[]> gradesRaw = gradesDao.getGradesForClass(classId, subjectId);
		
		Integer currentUser = null;
		
		LinkedHashMap<Users, List<Grades>> userGrades = new LinkedHashMap<Users, List<Grades>>();
		ArrayList<Grades> grades = new ArrayList<Grades>();
		
		for(Object[] item : gradesRaw) {
			
			if(currentUser == null) {
				currentUser = (Integer) item[2];
			}
			
			
			
			if(item[2] != currentUser) {
				Users user = usersDao.getOne(currentUser);
				user.setAverage(this.calculateAverage(grades));
				userGrades.put(user, grades);
				grades = new ArrayList<Grades>();
				
				currentUser = (Integer) item[2];
			}	
			
			Grades grade = new Grades();
			grade.setGradeValue((Integer)item[0]);
			grade.setGradeDescription((String)item[1]);
			grade.setGradeId((Integer)item[3]);
			grades.add(grade);
		}
		
		if(!grades.isEmpty()) {
			Users user = usersDao.getOne(currentUser);
			user.setAverage(this.calculateAverage(grades));
			userGrades.put(user, grades);
		}
		
		return userGrades;
	}

	public void save(Grades grade) {

		gradesDao.save(grade);
		
	}

	public void delete(Integer id) {

		Grades grade = gradesDao.getOne(id);
		if(grade != null) {
			gradesDao.delete(grade);
		}
		
	}

}
